package com.zxjbyte.yiyi.framework.mybatis.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 唯一性检查构建器
 * 适用于 多条件检查数据是否唯一
 * 例如：where name = '张三' and status = 0
 *
 * @Author zhangxingjia
 * @Date 2025/6/4 17:08
 * @Version: 1.0
 */
public class UniqueChecker<M extends BaseMapper<T>, T> {

    private final IService<T> service;
    private final Map<SFunction<T, ?>, Object> conditions = new LinkedHashMap<>();
    private Long ignoreId;

    private UniqueChecker(IService<T> service) {
        this.service = service;
    }

    public UniqueChecker<M, T> where(SFunction<T, ?> column, Object value) {
        conditions.put(column, value);
        return this;
    }

    public static <M extends BaseMapper<T>, T> UniqueChecker<M, T> of(IService<T> service) {
        return new UniqueChecker<>(service);
    }

    public UniqueChecker<M, T> ignoreId(Long id) {
        this.ignoreId = id;
        return this;
    }

    public boolean check() {
        QueryWrapper<T> query = Wrappers.query();
        conditions.forEach((k, v) ->
                query.eq(MybatisUtil.getColumnName(k, service.getEntityClass()), v));

        if (ignoreId != null) {
            query.ne("id", ignoreId);
        }
        return !service.exists(query);
    }
}
